package com.lazydong.gui_gateway.route;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.system.SystemUtil;
import com.alibaba.fastjson.JSONObject;
import com.lazydong.gui_gateway.GatewayApplication;
import com.lazydong.gui_gateway.gui.JFrameApp;
import com.lazydong.gui_gateway.model.ServiceIpAddr;
import com.lazydong.gui_gateway.model.ServiceRouteModel;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;

public class RouteConfigFileUtil {
    public static final LinkedHashMap<String, ServiceIpAddr> environmentMap = new LinkedHashMap<>();

    public static final LinkedHashMap<String, ServiceRouteModel> serviceServiceRouteModelMap = new LinkedHashMap<>();

    public static void initData() throws FileNotFoundException {
        String path = SystemUtil.getUserInfo().getCurrentDir() + "route.json";
        String readString = FileUtil.readString(path, CharsetUtil.CHARSET_UTF_8);
        JSONObject jsonMap = JSONObject.parseObject(readString);
        Integer port = jsonMap.getInteger("port");
        JFrameApp.portDef.set(port);
        String environmentJsonStr = jsonMap.getString("environment");
        List<ServiceIpAddr> environmentServiceIpAddrs = JSONObject.parseArray(environmentJsonStr, ServiceIpAddr.class);
        for (ServiceIpAddr serviceIpAddr : environmentServiceIpAddrs) {
            serviceIpAddr.setServiceName("environment");
            serviceIpAddr.setServiceId("environment");
            serviceIpAddr.setPredicate("/**");
            environmentMap.put(serviceIpAddr.getName(), serviceIpAddr);
        }

        String serviceJsonStr = jsonMap.getString("service");
        List<ServiceRouteModel> serviceRouteModels = JSONObject.parseArray(serviceJsonStr, ServiceRouteModel.class);
        for (ServiceRouteModel serviceRouteModel : serviceRouteModels) {
            serviceRouteModel.getList().forEach(temp -> {
                temp.setServiceName(serviceRouteModel.getServiceName());
                temp.setServiceId(serviceRouteModel.getServiceId());
                temp.setPredicate(serviceRouteModel.getPredicate());
            });
            serviceServiceRouteModelMap.put(serviceRouteModel.getServiceName(), serviceRouteModel);
        }
    }
}
